<template>
  <div>
    <Row>
      <i-col :span="9">
        <CellGroup @on-click="selectCatLevel1">
          <Cell :name="index" :title="item.title" :selected="index == c1Index" v-for="(item, index) in categoryTree" :key="index">
            <Badge :count="item.selectedCount" :overflow-count="99" type="error" slot="extra"></Badge>
          </Cell>
        </CellGroup>
      </i-col>

      <i-col span="14" offset="1">
        <div v-for="(c1, index1) in categoryTree" :key="index1" v-show="index1 == c1Index">
          <div v-for="(c2, index2) in c1.children" :key="index2">
            <div style="padding: 0.5rem 0.5rem;font-weight: 500;font-size: 13px">
              {{c2.title}}
            </div>
            <div v-for="(c3, index3) in c2.children" :key="index3" style="display: contents">
              <checkbox v-model="c3.checked" :disabled="c3.disabled" @on-change="checked => {selectCatLevel3(checked, index1, c3)}"
                        style="font-size: 13px;padding: 0.25rem 0.5rem;">
                {{c3.title}}
              </checkbox>
            </div>
          </div>
        </div>
      </i-col>
    </Row>
  </div>
</template>

<script>
import {getProductCommonData} from "../../js/commonUtils";
import {createCategoryTree} from "./js/categoryFuns";

export default {
  name: "CategoryTabs",
  props: {
    selectedCategories: {type: Array, default() {return []}},
  },
  model: {
    prop: "selectedCategories",
    event: "change"
  },
  data() {
    return {
      c1Index: 0,
      categoryTree: [],
    }
  },
  methods: {
    createCategoryTree(self, categoryTree) {
      createCategoryTree(self, categoryTree, this.selectedCategories)
    },
    selectCatLevel1(name) {
      let index = parseInt(name);
      this.c1Index = index;
    },
    selectCatLevel3(checked, index, c3) {
      if(checked) {
        this.categoryTree[index].selectedCount++;
        this.selectedCategories.push(c3.value);
      }else{
        if(this.categoryTree[index].selectedCount > 0) {
          this.categoryTree[index].selectedCount--;
        }
        let selectedIndex = this.selectedCategories.findIndex(item => item == c3.value);
        if(selectedIndex != -1) {
          this.selectedCategories.splice(selectedIndex,1);
        }
      }
    },
  },
  mounted() {
    getProductCommonData(this, this.categoryTree, [3], false, this.createCategoryTree);
  },
  watch: {
    "selectedCategories": {
      handler() {
        this.createCategoryTree(this, this.categoryTree, this.selectedCategories);
      },
    }
  }
}
</script>

<style scoped lang="less">
.ivu-cell-selected, .ivu-cell.ivu-cell-selected:hover {
  background-color: #c8e6c9;
}
</style>
